package com.zjitc.service.imp;

import com.github.pagehelper.PageHelper;
import com.google.gson.Gson;

import com.zjitc.dao.CategoryDao;
import com.zjitc.dao.ProductDao;
import com.zjitc.model.Category;
import com.zjitc.model.Product;
import com.zjitc.service.CategoryService;

import com.zjitc.utils.redis.MyRedis;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


/**
 * Create by IntelliJ IDEA
 *
 * @author: lhl
 * @date-Time: 2018/4/5 0005
 * @description:
 */
@Service
public class CategoryServiceImpl implements CategoryService {
    private static Logger logger = Logger.getLogger(CategoryServiceImpl.class);
    @Autowired
    private CategoryDao dao;
    @Autowired
    private ProductDao productDao;
    @Autowired
    private MyRedis redis;

    public Category jsonToObject(String str) {
        Gson gson = new Gson();
        Category category = gson.fromJson(str, Category.class);
        return category;
    }

    @Override
    public List<Category> findAll() {
        List<Category> categories = redis.allCategories();
        if (categories != null && !"".equals(categories)) {
            if (categories.size() != 0) {
                return redis.allCategories();
            }
        }
        logger.debug("redis数据出现问题，请维修人员尽快处理");
        return dao.findAll();
    }

    @Override
    public Category findByCid(String cid) {
        String one = redis.getOneById("categories", cid);
        return jsonToObject(one);
    }

    @Override
    public List<Category> findCategories(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Category> categories = dao.findAll();
        return categories;
    }

    @Override
    public void deleteByCid(String cid) {
        productDao.deleteByCid(cid);
        dao.deleteByCid(cid);
        List<Product> products = redis.allProducts();
        for (Product product : products) {
            if (cid.equals(product.getCid())) {
                redis.deleteById("products", product.getPid());
            }
        }
        redis.deleteById("categories", cid);
    }

    @Override
    public void add(Category category) {
        dao.add(category);
        Gson gson = new Gson();
        redis.addCathc("categories", category.getCid(), gson.toJson(category));
    }

    @Override
    public void update(Category category) {
        dao.update(category);
        Gson gson = new Gson();
        redis.alertById("categories", category.getCid(), gson.toJson(category));
    }
}
